package jwt

import (
	"fmt"
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

var jwtSecret = []byte(JWT_TOKEN_SignKey)

// 验证token的函数
func ParseToken(token string) (*CustomClaims, error) {
	tokenClaims, err := jwtgo.ParseWithClaims(token, &CustomClaims{}, func(token *jwtgo.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*CustomClaims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	//
	return nil, err
}

// 生成令牌
func GenerateToken(id int, account string, realname string) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour) // 过期时间
	claims := CustomClaims{
		id,
		account,
		realname,
		jwtgo.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}
	tokenClaims := jwtgo.NewWithClaims(jwtgo.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)
	return token, err
}

// GetDataByTime 一个需要token认证的测试接口
func GetDataByTime(c *gin.Context) {
	claims := c.MustGet("claims").(*CustomClaims)
	if claims != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 0,
			"msg":    "token有效",
			"data":   claims,
		})
	}
}

// 测试验证token
func TestValidToken() {
	token, _ := GenerateToken(1, "admin", "大总管")
	fmt.Println("生成的token:", token)
	claim, err := ParseToken(token)
	if err != nil {
		fmt.Println("解析token出现错误：", err)
	} else if time.Now().Unix() > claim.ExpiresAt {
		fmt.Println("时间超时")
	} else {
		fmt.Println("username:", claim.Account)
		fmt.Println("password:", claim.RealName)
	}
}
